package com.yy.glide.load.data;

import android.net.Uri;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlFetcher implements DataFetcher<InputStream> {
    private final Uri mUri;
    private boolean isCanceled;

    public HttpUrlFetcher(Uri uri) {
        mUri = uri;
    }

    @Override
    public void loadData(DataFetcherCallBack dataFetcher) {
        HttpURLConnection connection = null;
        InputStream is = null;

        try {
            URL url = new URL(mUri.toString());
            connection = (HttpURLConnection) url.openConnection();
            is = connection.getInputStream();
            int code = connection.getResponseCode();
            if (isCanceled) {
                return;
            }
            if (code == HttpURLConnection.HTTP_OK) {
                dataFetcher.onFetcherReady(is);
            } else {
                dataFetcher.onLoadFailed(new RuntimeException(connection.getResponseMessage()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    @Override
    public void cancel() {
        isCanceled = true;
    }
}
